#include "model_class.h"

#include "parser.h"
#include "dom_policy.h"

namespace model {
	typedef parser<dom_policy> dom_parser;
}

model::title* model::model_class::find_title(const string &file)
{
	title *t = 0;
	for(list<model::client>::iterator i = _clients.begin(); 
	    i != _clients.end(); ++i) {
		t = find_title(file, &(*i));
		if(t != 0) {
			return t;
		}
	}
	return t;
}

model::title* model::model_class::find_title(const string &file,
					     model::album *a)
{
	for(list<model::title>::iterator i  = a->get_titles().begin();
	    i != a->get_titles().end(); ++i) {
		if(i->get_filename() == file) {
			return &(*i);
		}
	}
	return 0;
}

model::title* model::model_class::find_title(const string &file, 
					     model::interpreter *inter)
{
	model::title *ptr = 0;

	for(list<model::album>::iterator i = inter->get_albums().begin();
	    i != inter->get_albums().end(); ++i) {
		ptr = find_title(file, &(*i));
		if(ptr) {
			break;
		}
	}
	return ptr;
}

model::title* model::model_class::find_title(const string &file, 
						model::client *clt)
{
	model::title *ptr = 0;

	for(list<model::interpreter>::iterator i  = 
	    clt->get_interpreters().begin();
	    i != clt->get_interpreters().end(); ++i) {
		ptr = find_title(file, &(*i));
		if(ptr) {
			break;
		}
	}
	return ptr;
}

model::client* model::model_class::find_client(const string &str)
{
	model::client *ptr = 0;
	for(list<model::client>::iterator i  = _clients.begin();
	    i != _clients.end(); ++i) {
		if(i->get_name() == str) {
			ptr = &(*i);
		}
	}
	return ptr;
}

boost::shared_ptr<boost::mutex> model::model_class::get_mutex()
{
	if(_mutex.get() == 0) {
		_mutex.reset(new boost::mutex);
	}
	return _mutex;
}

boost::shared_ptr<model::dom> model::model_class::to_dom() const
{
	typedef list<model::client>::const_iterator it;
	string tmp = "<music>";
	for(it i = _clients.begin(); i != _clients.end(); ++i) {
		tmp += i->to_xml();
	}
	tmp += "</music>";
	model::dom_parser pars;
	pars.parse(tmp);
	pars.get_node()->set_managed(false);
	return pars.get_node();
}

